<?php

/**
 * Table model class.
 *
 * @version  $Id: table.php 2 2009-10-02 23:06:43Z perfilev $
 * @package  System
 */

class Model_Table extends Model
{
	/**
	 * @var  array  Contains instances of database table.
	 */
	private static $instances = array();

	/**
	 * Return instance of Model_Table associated with
	 * specific database tale.
	 *
	 * @param   string  $table   Table name.
	 * @return  this
	 */
	public static function instance($table)
	{
		if (!array_key_exists($table, self::$instances)) {
			self::$instances[$table] = new Model_Table($table);
		}
		return self::$instances[$table];
	}

	/**
	 * @var  string  Table name.
	 */
	public $table;

	/**
	 * @var  array  Table primary and unique keys.
	 */
	public $keys = array(
		'integer' => 'id',
		'string'  => 'alias'
	);

	/**
	 * @var  string  Table primary key.
	 */
	public $primaryKey = 'id';

	/**
	 * @var  string  Column name, select result to be ordered on.
	 */
	public $orderCol = 'name';

	/**
	 * @var  string  Order direction.
	 */
	public $orderDir = 'ASC';

	/**
	 * Sets up table name and keys.
	 *
	 * @param   string  $table  Table name.
	 * @return  void
	 */
	public function __construct($table)
	{
		parent::__construct();
		$this->table = $table;
	}

	/**
	 * Sets order of select query.
	 *
	 * @param   string  $column     Column name.
	 * @param   string  $direction  Direction.
	 * @return  void
	 */
	public function setOrder($column, $direction = 'ASC')
	{
		$this->orderCol = $column;
		$this->orderDir = $direction;
	}

	/**
	 * Gets values from table.
	 *
	 * @param   mixed  $id  Key of 'WHERE' condition.
	 * @param   ...         Can accept offset and limit values.
	 * @return  void
	 */
	public function get($id = null)
	{
		if (2 == func_num_args()) {
			list($offset, $limit) = func_get_args();
			return $this->db->query('SELECT * FROM `' . $this->table . '` ORDER BY `' . $this->orderCol . '` ' . $this->orderDir . ' LIMIT ' . $limit . ', ' . $offset);
		}
		if (null === $id) {
			return $this->db->query('SELECT * FROM `' . $this->table . '` ORDER BY `' . $this->orderCol . '` ' . $this->orderDir);
		} else {
			return $this->db->query('SELECT * FROM `' . $this->table . '` WHERE `' . $this->keys[gettype($id)] . '` = ?', $id)->fetch();
		}
	}

    public function getByMail($id = null)
    {
        //system::dump($this->db->query('SELECT * FROM `' . $this->table . '` WHERE `email` = ?', $id)->fetch());exit();
        if (2 == func_num_args()) {
            list($offset, $limit) = func_get_args();
            return $this->db->query('SELECT * FROM `' . $this->table . '` ORDER BY `' . $this->orderCol . '` ' . $this->orderDir . ' LIMIT ' . $limit . ', ' . $offset);
        }
        if (null === $id) {
            return $this->db->query('SELECT * FROM `' . $this->table . '` ORDER BY `' . $this->orderCol . '` ' . $this->orderDir);
        } else {
            return $this->db->query('SELECT * FROM `' . $this->table . '` WHERE `email` = ?', $id)->fetch();
        }
    }

    public function addMember($eMail,$passwordEnc,$name=null,$surname=null,$role='member')
    {
        $name=isset($name)?$name:$eMail;
        $surname=isset($surname)?$surname:$eMail;
        //$this->db->query('SELECT * FROM `' . $this->table . '` WHERE `email` = ?', $id)->fetch();
        $mail2Check=substr($eMail, 0, 16);
        $validMail=$this->db->query('SELECT * FROM `' . $this->table . '` WHERE `email` = ?', $mail2Check)->fetch();
//        system::dump($validMail);exit();
        if($validMail==NULL){
            $this->db->query('INSERT INTO `users` (`name`,`password`,`fullName`,`email`,`role`)VALUES("'.rand(1000000000, 99999999999999).'","'.$passwordEnc.'","'.$eMail.'","'.$eMail.'","member")')->insertId();
            return true;
        }else{
            return false;
        }
    }
    public function editMail($uid,$newMail,$newPass=null,$oldPass=null)
    {
        if(!empty($newPass)){
            $this->db->query('UPDATE `users` SET `email`=?,`password`=? WHERE `id`=?', array($newMail,$newPass, $uid))->insertId();
            return 'Password and mail changed';
        }else{
            $this->db->query('UPDATE `users` SET `email`=? WHERE `id`=?', array($newMail, $uid))->insertId();
            return 'Mail changed';
        }
    }

	/**
	 * Checks if record exists in database and compare result with $testId, if exists.
	 *
	 * @param   mixed  $id      Key of 'WHERE' condition.
	 * @param   mixed  $testId  Value for comparision with primary key.
	 * @return  void
	 */
	public function exists($id, $testId = null)
	{
		if ($testId) {
			$result = $this->db->query('SELECT `' . $this->primaryKey . '` FROM `' . $this->table . '` WHERE `' . $this->keys[gettype($id)] . '` = ?', $id);
			return 0 != count($result) ? $testId != current($result->fetch()) : false;
		} else {
			$result = $this->db->query('SELECT `' . $this->primaryKey . '` FROM `' . $this->table . '` WHERE `' . $this->keys[gettype($id)] . '` = ?', $id);
			return 0 != count($result) ? true : false;
		}
	}

	/**
	 * Insert values in database.
	 *
	 * @param   array  $values  Values for insertion.
	 * @return  Database_Result
	 */
	public function insert(array $values)
	{
		if (0 === count($values)) return null;
		return $this->db->insert($this->table, $values);
	}

	/**
	 * Updates record with key $id.
	 *
	 * @param   array  $values  Values to be updated.
	 * @param   mixed  $id      Key for update.
	 * @return  Database_Result
	 */
	public function update(array $values, $id)
	{
		if (0 === count($values)) return null;
		return $this->db->update($this->table, $values, array($this->keys[gettype($id)] => $id));
	}


	/**
	 * Deletes record from table
	 *
	 * @param   mixed  $id  Key for delete.
	 * @return  void
	 */
	public function delete($id)
	{
		return $this->db->query('DELETE FROM `' . $this->table . '` WHERE `' . $this->keys[gettype($id)] . '` = ?', $id)->count();
	}
}
